package com.example.demo.leetcode.classics150;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _106括号生成
 * @description
 * @date 2023/08/12 21:19
 * <p>
 * ******************************************************
 */
public class _106括号生成 {

    List<String> res = new LinkedList<>();
    StringBuilder track = new StringBuilder();
    char[] chars = new char[]{'(', ')'};


    public List<String> generateParenthesis(int n) {
        if (n <= 0) {
            return res;
        }
        backtrack(n, n, n);
        return res;
    }

    private void backtrack(int n, int left, int right) {
        if (left == 0 && right == 0) {
            res.add(track.toString());
            return;
        }
        // 说明右括号已经多了
        if (left > right) {
            return;
        }
        if (left > 0) {
            track.append(chars[0]);
            backtrack(n, left - 1, right);
            track.deleteCharAt(track.length() - 1);
        }

        if (right > 0) {
            track.append(chars[1]);
            backtrack(n, left, right - 1);
            track.deleteCharAt(track.length() - 1);
        }


    }
}
